import Foundation

import Alamofire

public enum ReachabilityStatus {
    /// It is unknown whether the network is reachable.
    case unknown
    /// The network is not reachable.
    case notReachable
    /// The connection type is either over Ethernet or WiFi.
    case ethernetOrWiFi
    /// The connection type is a cellular connection.
    case cellular
}

public let kNetworkStatusNotification = NSNotification.Name("kNetworkStatusNotification")

let apiProvider = MoyaProvider<NetWorkBaseApi>()
//var apiProvider = AppProvider.createAuthProvider()

extension MoyaProvider where Target == NetWorkBaseApi {
    @discardableResult
    func request(api: NetWorkBaseApi, successHandler: (([String: Any],[[String: Any]] ,Int) -> Void)? = nil, failureHandler: ((Error) -> Void)? = nil) -> Cancellable {
        return request(api) { (result) in
            switch result {
            case .failure(_):
                successHandler?([:],[[:]],-1)
            case .success(let response):
                do {
                    let code = response.response?.statusCode

                    if code == 200 {

                        var json: Any = ["code":0]
                        do {
                            json = try response.mapJSON()
                        } catch {

                        }

                        // print("请求数据json-\(json)")
                        if var dict = json as? [String:Any] {
                            // print("请求数据 ---- \(dict)")

                            if let scode = dict["code"] {
                                let scodeStr = "\(scode)"
                                if scodeStr == "401" {
                                    DispatchQueue.main.async {
                                        //print("未拦截到401！！！！！")
                                        if !(Utils.getTopVC() is LoginVC ){
                                            kUserManager.logoutClearData()
                                            //kUserManager.toLogin()
                                        }
                                    }
                                    dict["msg"] = "登录信息已过期，请重新登录！"
                                }
                            }

                            successHandler?(dict, [], code ?? 0)

                        } else if let dict = json as? [[String:Any]] {
                            // print("请求数据数组 ---- \(dict)")
                            successHandler?([:], dict, code ?? 0)
                        } else {
                            successHandler?([:], [], code ?? 0)
                        }


                    }else if code == 400 || code == 401 {

                        DispatchQueue.main.async {
                            if code == 401 {
                                // 重新登录
                                print("未拦截到401！！！！！")
                                if !(Utils.getTopVC() is LoginVC ){
                                    kUserManager.logoutClearData()
                                    //kUserManager.toLogin()
                                }
                            } else {
                                print("解析失败！！！")
                                Utils.getTopVC()?.showMessage(message: "网络开小差了。")
                            }
                        }

                    }else{
                        successHandler?([:],[[:]],code ?? 0)
                    }
                } catch let error {
                    print("服务器返回状态码 --- \(error.localizedDescription)")
                    successHandler?([:],[[:]],500)
                    DispatchQueue.main.async {
//                        Utils.getTopVC()?.showMessage(message: "网络开小差了。", afterDelay: kHUDTime)
                    }
                    //                    DispatchQueue.main.async {
                    //                        AlertView.init(imageName: Constant.noNetworkpopshow, bg: Constant.defaultBg, message: error.localizedDescription).show()
                    //                    }
                }
            }
        }
    }

    // MARK: - 表单上传参数
    func requetFormData(url: String, param: [String: Any], successHandler: (([String: Any],[[String: Any]] ,Int) -> Void)? = nil, failureHandler: ((Error) -> Void)? = nil) {

        AF.upload(multipartFormData: { MultipartFormData in
            //MultipartFormData.append(fileContent, withName: "file" , fileName: filePath.lastPathComponent , mimeType: "image/jpeg")
            for(key,value) in param {

                if let dataStr = value as? String, let finalStr = dataStr.data(using: .utf8) {
                    MultipartFormData.append(finalStr, withName: key)
                } else if let dataStr = value as? Int {
                    var send1: Int = dataStr
                    MultipartFormData.append(Data(bytes: &send1, count: 8), withName: key)
                }
            }
        }, to: url, method: .put, headers: ["Content-Type": "application/json","Authorization":kUserManager.accessToken]).responseString { response in
            print(response)
        }

    }

}

// MARK: - 网络监测
protocol NetWorkReachabilityDelegate: NSObjectProtocol {
    func networkStatusChange(status: ReachabilityStatus)
}
final class NetWorkManager {
    
    static let shared = NetWorkManager()
    /**网络监控**/
    var reachability: NetworkReachabilityManager?
    var networkStatus: ReachabilityStatus = .unknown
    weak var delegate: NetWorkReachabilityDelegate?
    private init() {}
    
    /// Starts monitoring for changes in network reachability status.
    public func startMonitoring() {
        if reachability == nil {
            reachability = NetworkReachabilityManager.default
        }

        reachability?.startListening(onQueue: .main, onUpdatePerforming: { [unowned self] (status) in
            switch status {
            case .notReachable:
                self.networkStatus = .notReachable
            case .unknown:
                self.networkStatus = .unknown
            case .reachable(.ethernetOrWiFi):
                self.networkStatus = .ethernetOrWiFi
            case .reachable(.cellular):
                self.networkStatus = .cellular
            }
            // Sent notification
            NotificationCenter.default.post(name: kNetworkStatusNotification, object: nil)
            // 获取广告Id
            AlbumPermissionsManager.getIdfa()
            debugPrint("QFNetworking Network Status: \(self.networkStatus)")
        })
    }

    /// Stops monitoring for changes in network reachability status.
    public func stopMonitoring() {
        guard reachability != nil else { return }
        reachability?.stopListening()
    }
}



